package com.jason.www.widget.dialogfragment;

import android.view.View;
import android.widget.TextView;

import com.jason.www.R;
import com.jason.www.adapter.TextAdapter;
import com.jason.www.widget.itemdecoration.CommonItemDecoration;

import java.util.Arrays;
import java.util.List;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;
import butterknife.OnClick;

/**
 * @author：Jason
 * @date：2020/12/29 11:15
 * @email：1129847330@qq.com
 * @description:
 */
public class ListDialogFragment extends BaseDialogFragment {
    @BindView(R.id.recyclerview)
    protected RecyclerView recyclerview;
    @BindView(R.id.tv_left)
    protected TextView tvLeft;
    @BindView(R.id.tv_right)
    protected TextView tvRight;
    protected TextAdapter mAdapter;
    private List<String> totallist;
    private int mCurrentPosition;
    private String mTitle;

    @Override
    protected void initView(View view) {
        super.initView(view);
        recyclerview.setLayoutManager(new LinearLayoutManager(mContext));
        mAdapter = new TextAdapter();
        recyclerview.addItemDecoration(CommonItemDecoration.createVertical());
        recyclerview.setAdapter(mAdapter);
        mAdapter.setList(totallist);
        tvLeft.setText(mTitle);
    }

    @Override
    protected void initEvent() {
        super.initEvent();
        mAdapter.setOnItemClickListener((adapter, view, position) -> {
            mCurrentPosition = position;
            if (onItemClickListener != null) {
                onItemClickListener.onItemClicked(position, mAdapter.getData().get(position));
            }
            dismiss();
        });
    }

    public void updateList(List<String> list) {
        totallist = list;
        if (mAdapter != null) {
            mAdapter.setList(list);
        }
    }

    public void updateList(String[] array) {
        totallist = Arrays.asList(array);
        if (mAdapter != null) {
            mAdapter.setList(totallist);
        }
    }

    public void setTitle(String title) {
        this.mTitle = title;
    }

    public void setHeight(int height) {
        mHeight = height;
    }

    private int mHeight;

    @Override
    public int getHeight() {
        return mHeight == 0 ? super.getHeight() : mHeight;
    }

    @Override
    protected int getLayoutRes() {
        return R.layout.dialog_list;
    }

    @OnClick(R.id.tv_right)
    public void onViewClicked() {
        if (onItemClickListener != null) {
            onItemClickListener.onItemClicked(mCurrentPosition, mAdapter.getData().get(mCurrentPosition));
        }
        dismiss();
    }

    public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
        this.onItemClickListener = onItemClickListener;
    }

    private OnItemClickListener onItemClickListener;

    public interface OnItemClickListener {
        void onItemClicked(int position, String str);
    }
}